import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useDebouncedFunction, useCache } from '../composables'
import type { 
  SearchResult, 
  ContentSearchResult, 
  SearchOptions, 
  ContentSearchOptions,
  SearchCriteria 
} from '../types/basic'
import { searchEngine } from '../services'

export const useSearchStore = defineStore('search', () => {
  // State
  const query = ref('')
  const searchType = ref<'filename' | 'content' | 'advanced'>('filename')
  const results = ref<SearchResult[]>([])
  const contentResults = ref<ContentSearchResult[]>([])
  const searchHistory = ref<string[]>([])
  const isSearching = ref(false)
  const error = ref<string | null>(null)
  const totalResults = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(50)
  
  // 缓存实例
  const searchCache = useCache<SearchResult[] | ContentSearchResult[]>({
    maxSize: 200,
    defaultTTL: 5 * 60 * 1000 // 5分钟缓存
  })
  
  // Search options
  const searchOptions = ref<SearchOptions>({
    caseSensitive: false,
    exactMatch: false,
    fileTypes: [],
    versionIds: [],
    maxResults: 1000
  })
  
  const contentSearchOptions = ref<ContentSearchOptions>({
    ...searchOptions.value,
    contextLines: 2,
    regex: false
  })
  
  const advancedCriteria = ref<SearchCriteria>({
    fileName: '',
    content: '',
    fileType: '',
    dateRange: undefined,
    sizeRange: undefined,
    versionIds: []
  })

  // Getters
  const hasResults = computed(() => 
    results.value.length > 0 || contentResults.value.length > 0
  )

  const paginatedResults = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    
    if (searchType.value === 'content') {
      return contentResults.value.slice(start, end)
    }
    return results.value.slice(start, end)
  })

  const totalPages = computed(() => 
    Math.ceil(totalResults.value / pageSize.value)
  )

  const hasNextPage = computed(() => currentPage.value < totalPages.value)
  const hasPrevPage = computed(() => currentPage.value > 1)

  const recentSearches = computed(() => 
    searchHistory.value.slice(-10).reverse()
  )

  // 防抖搜索函数
  const debouncedSearchByFileName = useDebouncedFunction(
    async (searchQuery: string, options?: Partial<SearchOptions>) => {
      await performSearchByFileName(searchQuery, options)
    },
    300
  )
  
  const debouncedSearchByContent = useDebouncedFunction(
    async (searchQuery: string, options?: Partial<ContentSearchOptions>) => {
      await performSearchByContent(searchQuery, options)
    },
    500 // 内容搜索使用更长的防抖时间
  )

  // Actions
  async function searchByFileName(searchQuery: string, options?: Partial<SearchOptions>) {
    if (!searchQuery.trim()) {
      clearResults()
      return
    }
    
    // 使用防抖搜索
    await debouncedSearchByFileName(searchQuery, options)
  }
  
  async function performSearchByFileName(searchQuery: string, options?: Partial<SearchOptions>) {
    const mergedOptions = { ...searchOptions.value, ...options }
    const cacheKey = `filename:${searchQuery}:${JSON.stringify(mergedOptions)}`
    
    try {
      isSearching.value = true
      error.value = null
      searchType.value = 'filename'
      
      // 检查缓存
      const cachedResults = searchCache.get(cacheKey) as SearchResult[] | null
      if (cachedResults) {
        results.value = cachedResults
        contentResults.value = []
        totalResults.value = cachedResults.length
        currentPage.value = 1
        addToSearchHistory(searchQuery)
        return
      }
      
      const searchResults = await searchEngine.searchByFileName(searchQuery, mergedOptions)
      
      // 缓存结果
      searchCache.set(cacheKey, searchResults)
      
      results.value = searchResults
      contentResults.value = []
      totalResults.value = searchResults.length
      currentPage.value = 1
      
      addToSearchHistory(searchQuery)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '文件名搜索失败'
      console.error('Search by filename failed:', err)
    } finally {
      isSearching.value = false
    }
  }

  async function searchByContent(searchQuery: string, options?: Partial<ContentSearchOptions>) {
    if (!searchQuery.trim()) {
      clearResults()
      return
    }
    
    // 使用防抖搜索
    await debouncedSearchByContent(searchQuery, options)
  }
  
  async function performSearchByContent(searchQuery: string, options?: Partial<ContentSearchOptions>) {
    const mergedOptions = { ...contentSearchOptions.value, ...options }
    const cacheKey = `content:${searchQuery}:${JSON.stringify(mergedOptions)}`
    
    try {
      isSearching.value = true
      error.value = null
      searchType.value = 'content'
      
      // 检查缓存
      const cachedResults = searchCache.get(cacheKey) as ContentSearchResult[] | null
      if (cachedResults) {
        contentResults.value = cachedResults
        results.value = []
        totalResults.value = cachedResults.length
        currentPage.value = 1
        addToSearchHistory(searchQuery)
        return
      }
      
      const searchResults = await searchEngine.searchByContent(searchQuery, mergedOptions)
      
      // 缓存结果
      searchCache.set(cacheKey, searchResults)
      
      contentResults.value = searchResults
      results.value = []
      totalResults.value = searchResults.length
      currentPage.value = 1
      
      addToSearchHistory(searchQuery)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '内容搜索失败'
      console.error('Search by content failed:', err)
    } finally {
      isSearching.value = false
    }
  }

  async function advancedSearch(criteria?: Partial<SearchCriteria>) {
    const searchCriteria = { ...advancedCriteria.value, ...criteria }
    
    // Validate criteria
    if (!searchCriteria.fileName && !searchCriteria.content) {
      error.value = '请至少输入文件名或内容搜索条件'
      return
    }

    try {
      isSearching.value = true
      error.value = null
      searchType.value = 'advanced'
      
      const searchResults = await searchEngine.advancedSearch(searchCriteria)
      
      results.value = searchResults
      contentResults.value = []
      totalResults.value = searchResults.length
      currentPage.value = 1
      
      const queryStr = buildQueryString(searchCriteria)
      addToSearchHistory(queryStr)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '高级搜索失败'
      console.error('Advanced search failed:', err)
    } finally {
      isSearching.value = false
    }
  }

  async function buildSearchIndex() {
    try {
      isSearching.value = true
      error.value = null
      await searchEngine.buildIndex()
    } catch (err) {
      error.value = err instanceof Error ? err.message : '构建搜索索引失败'
      console.error('Build search index failed:', err)
    } finally {
      isSearching.value = false
    }
  }

  function setQuery(newQuery: string) {
    query.value = newQuery
  }

  function setSearchType(type: 'filename' | 'content' | 'advanced') {
    searchType.value = type
    clearResults()
  }

  function updateSearchOptions(options: Partial<SearchOptions>) {
    searchOptions.value = { ...searchOptions.value, ...options }
  }

  function updateContentSearchOptions(options: Partial<ContentSearchOptions>) {
    contentSearchOptions.value = { ...contentSearchOptions.value, ...options }
  }

  function updateAdvancedCriteria(criteria: Partial<SearchCriteria>) {
    advancedCriteria.value = { ...advancedCriteria.value, ...criteria }
  }

  function clearResults() {
    results.value = []
    contentResults.value = []
    totalResults.value = 0
    currentPage.value = 1
    error.value = null
  }
  
  function clearSearchCache() {
    searchCache.clear()
  }
  
  function getSearchCacheStats() {
    return searchCache.stats
  }

  function clearSearchHistory() {
    searchHistory.value = []
  }

  function removeFromSearchHistory(queryToRemove: string) {
    const index = searchHistory.value.indexOf(queryToRemove)
    if (index > -1) {
      searchHistory.value.splice(index, 1)
    }
  }

  async function batchRecover(results: (SearchResult | ContentSearchResult)[]) {
    // This should integrate with the recovery store
    // For now, just emit the results to be handled by the parent component
    return results
  }

  function goToPage(page: number) {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page
    }
  }

  function nextPage() {
    if (hasNextPage.value) {
      currentPage.value++
    }
  }

  function prevPage() {
    if (hasPrevPage.value) {
      currentPage.value--
    }
  }

  function setPageSize(size: number) {
    pageSize.value = size
    currentPage.value = 1
  }

  function clearError() {
    error.value = null
  }

  // Helper functions
  function addToSearchHistory(searchQuery: string) {
    if (!searchQuery.trim()) return
    
    // Remove if already exists
    const index = searchHistory.value.indexOf(searchQuery)
    if (index > -1) {
      searchHistory.value.splice(index, 1)
    }
    
    // Add to beginning
    searchHistory.value.unshift(searchQuery)
    
    // Keep only last 50 searches
    if (searchHistory.value.length > 50) {
      searchHistory.value = searchHistory.value.slice(0, 50)
    }
  }

  function buildQueryString(criteria: SearchCriteria): string {
    const parts: string[] = []
    
    if (criteria.fileName) parts.push(`文件名:${criteria.fileName}`)
    if (criteria.content) parts.push(`内容:${criteria.content}`)
    if (criteria.fileType) parts.push(`类型:${criteria.fileType}`)
    if (criteria.dateRange) {
      parts.push(`时间:${criteria.dateRange.start.toLocaleDateString()}-${criteria.dateRange.end.toLocaleDateString()}`)
    }
    if (criteria.sizeRange) {
      parts.push(`大小:${criteria.sizeRange.min}-${criteria.sizeRange.max}`)
    }
    
    return parts.join(' ')
  }

  return {
    // State
    query,
    searchType,
    results,
    contentResults,
    searchHistory,
    isSearching,
    error,
    totalResults,
    currentPage,
    pageSize,
    searchOptions,
    contentSearchOptions,
    advancedCriteria,
    
    // Getters
    hasResults,
    paginatedResults,
    totalPages,
    hasNextPage,
    hasPrevPage,
    recentSearches,
    
    // Actions
    searchByFileName,
    searchByContent,
    advancedSearch,
    buildSearchIndex,
    setQuery,
    setSearchType,
    updateSearchOptions,
    updateContentSearchOptions,
    updateAdvancedCriteria,
    clearResults,
    clearSearchHistory,
    removeFromSearchHistory,
    batchRecover,
    goToPage,
    nextPage,
    prevPage,
    setPageSize,
    clearError,
    clearSearchCache,
    getSearchCacheStats
  }
})